package com.cmwa.scbp.utils.cached;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.cmwa.scbp.base.exception.CachedException;
import com.cmwa.scbp.sys.userInfo.entity.UserInfoVo;
import com.cmwa.scbp.sys.userInfo.service.UserInfoService;
import com.cmwa.scbp.utils.cached.service.ShareCachedService;

@Component
public class EmployeeCached implements ShareCachedService, InitializingBean {
	@Resource
	UserInfoService userInfoService;
	private static Map<String, String> empIdAndNameCached = new HashMap<String, String>(1024);
	
	/**
	 * 用户信息缓存集合
	 */
	private static List<UserInfoVo> userInfoList = new Vector<UserInfoVo>();

	@Override
	public void afterPropertiesSet() throws Exception {
		loadMappingCached();
	}

	/**
	 * {@link} IBF_GET_EMPNAME_BY_ID()
	 * 根据员工ID取得员工名字
	 * @param empId
	 * @return
	 */
	public static String getName(String empId) {
		String name=empIdAndNameCached.get(empId);
		return name==null?empId:name;
	}

	@Override
	public void loadMappingCached() throws CachedException {
		empIdAndNameCached.clear();
		UserInfoVo userInfo = new UserInfoVo();
		if (userInfoList != null) {
			userInfoList.clear();
		}
		userInfoList = userInfoService.searchUserInfoList(userInfo);
		for (UserInfoVo userInfoVo : userInfoList) {
			empIdAndNameCached.put(userInfoVo.getEmpID(), userInfoVo.getEmpName());
		}
	}

	/**
	 * 模糊匹配
	 * @param empName
	 * @param queryDimission
	 * @return
	 */
	public static List<UserInfoVo> getUserInfosByName(String empName, boolean queryDimission) {
		List<UserInfoVo> vList = new Vector<UserInfoVo>();
		// 2018-05-18 modify by hejm 
		// 由于我是用的#做占位，如果直接查询#会查询出全部的，效率极低
		// 而且一般情况下查询条件中也不应该出现#，所以我这里直接就将它过滤掉
		if ((userInfoList == null || userInfoList.size() == 0 || StringUtils.equals(empName, "#"))) {
			return vList;
		} else {
			for (int i = 0; i < userInfoList.size(); i++) {
				UserInfoVo vo = (UserInfoVo) userInfoList.get(i);
				//过滤状态为空或者已删除的
//				if (StringUtils.isEmpty(vo.getEmpStat()) || "DELE".equalsIgnoreCase(vo.getEmpStat())) {
//					continue;
//				}
				//构建名称
				String name = buildQueryName(vo);
				int searchOrder = name.indexOf(empName); 
				if (searchOrder > -1) {
					vo.setSearchOrder(searchOrder);
					if (!queryDimission) {
							if(filterDismission(vo)){
								vList.add(vo);
							}
					}else{
							vList.add(vo);
					}	
				}
			}
			Collections.sort(vList, new Comparator<UserInfoVo>() {
				@Override
				public int compare(UserInfoVo o1, UserInfoVo o2) {
					return o1.getSearchOrder() - o2.getSearchOrder();
				}
			});
			return vList;
		}
	}
	
	/**
	 * @param 项目经理搜索重构
	 * @param queryDimission
	 * @param onlyEmpName 
	 * @return
	 */
	public static List<UserInfoVo> getUserInfosByName(String empName, boolean queryDimission, boolean cleanDele) {
		List<UserInfoVo> vList = new Vector<UserInfoVo>();
		// 2018-05-18 modify by hejm 
		// 由于我是用的#做占位，如果直接查询#会查询出全部的，效率极低
		// 而且一般情况下查询条件中也不应该出现#，所以我这里直接就将它过滤掉
		if ((userInfoList == null || userInfoList.size() == 0 || StringUtils.equals(empName, "#"))) {
			return vList;
		} else {
			for (int i = 0; i < userInfoList.size(); i++) {
				UserInfoVo vo = (UserInfoVo) userInfoList.get(i);
				String name = "";
				name = buildQueryName(vo);
				int searchOrder = name.indexOf(empName); 
				if (searchOrder > -1) {
					vo.setSearchOrder(searchOrder);
					// 不查询离职人员，过滤vo
					if (!queryDimission) {
						if (filterDismission(vo)) {
							vList.add(vo);
						}
					} else {
						if (!cleanDele) {
							vList.add(vo);
						} else {
							// 过滤已删除状态人员
							if (vo != null && !StringUtils.equals(vo.getEmpStat(), "DELE")) {
								vList.add(vo);
							}
						}
					}
				}
			}
			Collections.sort(vList, new Comparator<UserInfoVo>() {
				@Override
				public int compare(UserInfoVo o1, UserInfoVo o2) {
					return o1.getSearchOrder() - o2.getSearchOrder();
				}
			});
			return vList;
		}
	}
	
	/**
	 * 查询没有重名的人员信息
	 * 
	 * @param empName
	 * @param queryDimission
	 * @return
	 */
	public static List<UserInfoVo> getDuplicateUserInfosByName(String empName, boolean queryDimission, boolean cleanDele) {
		Map<String, UserInfoVo> vMap = new HashMap<String, UserInfoVo>();
		// 2018-05-18 modify by hejm 
		// 由于我是用的#做占位，如果直接查询#会查询出全部的，效率极低
		// 而且一般情况下查询条件中也不应该出现#，所以我这里直接就将它过滤掉
		if ((userInfoList == null || userInfoList.size() == 0 || StringUtils.equals(empName, "#"))) {
			return asList(vMap);
		} else {
			for (int i = 0; i < userInfoList.size(); i++) {
				UserInfoVo vo = (UserInfoVo) userInfoList.get(i);
				String name = "";
				name = buildQueryName(vo);
				int searchOrder = name.indexOf(empName); 
				if (searchOrder > -1) {
					vo.setSearchOrder(searchOrder);
					// 不查询离职人员，过滤vo
					if (!queryDimission) {
						if (filterDismission(vo)) {
							vMap.put(vo.getEmpID(), vo);
						}
					} else {
						if (!cleanDele) {
							vMap.put(vo.getEmpID(), vo);
						} else {
							// 过滤已删除状态人员
							if (vo != null && !StringUtils.equals(vo.getEmpStat(), "DELE")) {
								vMap.put(vo.getEmpID(), vo);
							}
						}
					}
				}
			}
			List<UserInfoVo> result = asList(vMap);
			Collections.sort(result, new Comparator<UserInfoVo>() {
				@Override
				public int compare(UserInfoVo o1, UserInfoVo o2) {
					return o1.getSearchOrder() - o2.getSearchOrder();
				}
			});
			return result;
		}
	}
	
	/**
	 * 根据登录名或名称精准匹配
	 * @param name
	 * @return
	 */
	public static List<UserInfoVo> getUserInfoByEmpNameorLoginName(String name){

		List<UserInfoVo> vList = new Vector<UserInfoVo>();
		if ((userInfoList == null || userInfoList.size() == 0)) {
			return vList;
		} else {
			for (int i = 0; i < userInfoList.size(); i++) {
				UserInfoVo vo = (UserInfoVo) userInfoList.get(i);
				
				//过滤状态为空或者已删除的
				if (StringUtils.isEmpty(vo.getEmpStat()) || "DELE".equalsIgnoreCase(vo.getEmpStat()) || StringUtils.isEmpty(vo.getEmpName())
						|| StringUtils.isEmpty(vo.getLogin())) {
					continue;
				}
				//登录名，名称匹配
				if (name.equalsIgnoreCase(vo.getEmpName()) || name.equalsIgnoreCase(vo.getLogin())) {
					vList.add(vo);
				}
			}
			
			//把list中通一个empid的对象去重
			List<UserInfoVo> resList = removeDuplicateUser(vList);
			if(resList.size() > 0){
				vList.clear();
				vList = resList;
			}
			return vList;
		}
	
	}
	private static boolean filterDismission(UserInfoVo vo) {
		if (vo != null && StringUtils.equals(vo.getEmpStat(), "STAR") && StringUtils.equals(vo.getOrmemberStat(), "STAR")) {
			return true;
		}
		return false;
	}
	
	/**
	 * 根据id获取登录名
	 * @param id
	 * @return
	 */
	public static String getEmpLoginNameById(String id){
		if ((userInfoList == null || userInfoList.size() == 0)) {
			return null;
		} else {
			for (int i = 0; i < userInfoList.size(); i++) {
				UserInfoVo vo = (UserInfoVo) userInfoList.get(i);
				//过滤状态为空或者已删除的
				if (StringUtils.isEmpty(vo.getEmpStat()) || "DELE".equalsIgnoreCase(vo.getEmpStat()) || StringUtils.isEmpty(vo.getEmpName())
						|| StringUtils.isEmpty(vo.getLogin())) {
					continue;
				}
				if (id.equals(vo.getEmpID())) {
					return vo.getEmpSName();
				}
				
			}
		}
		return null;
	}
	
	/**
	 * 根据用户ID查询信息
	 * @author ex-hejm
	 * @date 2018年10月24日 下午5:38:22
	 * @param empId            用户ID
	 * @param queryDimission   是否查询离职人员 true是不查，false查
	 * @param cleanDele        是否查询已删除人员 true是查，false不查
	 * @return
	 */
	public static List<UserInfoVo> getUserInfosByEmpId(String empId, boolean queryDimission, boolean cleanDele) {
		List<UserInfoVo> vList = new Vector<UserInfoVo>();
		if (userInfoList == null || userInfoList.size() == 0) {
			return vList;
		} else {
			for (int i = 0; i < userInfoList.size(); i++) {
				UserInfoVo vo = (UserInfoVo) userInfoList.get(i);
				String empIdTemp = vo.getEmpID(); 
				if(StringUtils.equals(empId, empIdTemp)) {
					// 不查询离职人员，过滤vo
					if (!queryDimission) {
						if (filterDismission(vo)) {
							vList.add(vo);
						}
					} else {
						if (!cleanDele) {
							vList.add(vo);
						} else {
							// 过滤已删除状态人员
							if (vo != null && !StringUtils.equals(vo.getEmpStat(), "DELE")) {
								vList.add(vo);
							}
						}
					}
				}
			}
			return vList;
		}
	}
	
	/**
	 * 根据多个员工id取得员工姓名，多个员工id用,隔开
	 * @author ex-weicb
	 * @createDate 2016年4月29日 下午3:08:02
	 * @param empIds
	 * @return
	 */
	public static String getAllName(String empIds) {
		if (StringUtils.isEmpty(empIds)) {
			return "";
		}
		String[] empIdList=empIds.split(",");
		StringBuffer allNames=new StringBuffer();
		for (int i = 0; i < empIdList.length; i++) {
			String prefix=",";
			if (i==0) 
				prefix="";
			
			String name=empIdAndNameCached.get(empIdList[i]);
			allNames.append(prefix+(name==null? "":name));
		}
		return allNames.toString();
	}
	
	public static String getEmpIdByName(String empName) {
		//同名同姓先不处理,因未提供身份证唯一标识
		String empId = "";
		for(String key :empIdAndNameCached.keySet()){
			String name = empIdAndNameCached.get(key);
			if(empName.equals(name)){
				empId = key;
				break;
			}
		}
		return empId;
	}
	
	/**
	 * 构建查询的名称
	 * 
	 * @param vo
	 * @return
	 */
	public static String buildQueryName(UserInfoVo vo) {
		String name = "";
		// 2018-05-18 17:22 modify by hejm start
		// 现在要用下面的追加顺序来对搜索出来的用户列表进行排序
		// 目前解决方案是用indexOf来排序，但是存在用户名长短不一致问题，界面显示不好看，所以统一10位长度
		if(vo.getEmpName() != null) {
			StringBuilder empName = new StringBuilder(vo.getEmpName());
			int empNameLen = empName.length(); 
			if (empNameLen > 0) {
				if(empNameLen < 10) {
					for(int i = 0; i < 10 - empNameLen; i++) {
						empName.append("#");
					}
				}
				name += empName;
			}
		}
		// 2018-05-18 17:22 modify by hejm end
		if (vo.getEmpSName() != null) {
			name += vo.getEmpSName();
		}
		if (vo.getReOrgName() != null) {
			name += vo.getReOrgName();
		}
		if (vo.getOrgName() != null) {
			name += vo.getOrgName();
		}
		if (vo.getSecondOrgname() != null) {
			name += vo.getSecondOrgname();
		}
		if (vo.getTitleName() != null) {
			name += vo.getTitleName();
		}
		return name;
	}
	
	/**
	 * map转为list
	 * 
	 * @param userMap
	 * @return
	 */
	private static List<UserInfoVo> asList(Map<String, UserInfoVo> userMap) {
		List<UserInfoVo> list = new ArrayList<UserInfoVo>();
		for (UserInfoVo vo : userMap.values()) {
			list.add(vo);
		}
		return list;
	}
	
	/**
	 * 把list同一个员工去重复
	 * 
	 * @param userMap
	 * @return
	 */
    private static ArrayList<UserInfoVo> removeDuplicateUser(List<UserInfoVo> users) {
        Set<UserInfoVo> set = new TreeSet<UserInfoVo>(new Comparator<UserInfoVo>() {
            @Override
            public int compare(UserInfoVo o1, UserInfoVo o2) {
                //字符串,则按照asicc码升序排列
                return o1.getEmpID().compareTo(o2.getEmpID());
            }
        });
        set.addAll(users);
        return new ArrayList<UserInfoVo>(set);
   }
    
    public static String getEmpTelOff(String empId) {
    	String empTelOff = "";
    	for (UserInfoVo userInfo : userInfoList) {
    		if (StringUtils.equals(empId, userInfo.getEmpID())) {
    			empTelOff = userInfo.getEmpTelOff();
    		}
    	}
    	return empTelOff;
    }
    
    public static String getFirstEmpTelOff(String empIds) {
    	if (StringUtils.isEmpty(empIds)) {
			return "";
		}
		String[] empIdList = empIds.split(",");
		if (empIdList.length <= 0) {
			return "";
		}
    	String empTelOff = "";
    	for (UserInfoVo userInfo : userInfoList) {
    		if (StringUtils.equals(empIdList[0], userInfo.getEmpID())) {
    			empTelOff = userInfo.getEmpTelOff();
    		}
    	}
    	return empTelOff;
    }
    
}
